package com.hsnr.familyfinder;

import java.util.HashMap;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;

public class UpdateService extends Service implements LocationListener {
    private ConnectionHandler ch;
    private HashMap<String, String> coordinates;
    private double longitude, latitude, height;
    // eine Minute Wartezeit. Bei Bedarf anpassen
    private final String TAG = "FamilyFinder";
    long minutes;
    String provider;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

        MyLog.d(TAG, "Service aufgerufen");
        final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        minutes = Integer.parseInt(sharedPrefs.getString("intervall", "10")) * 1000 * 60;
        MyLog.d(TAG, "minutes <" + minutes + ">");
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria c = new Criteria();
        c.setAccuracy(Criteria.POWER_LOW);

        provider = lm.getBestProvider(c, true);
        if (provider == null)
            provider = LocationManager.GPS_PROVIDER;
        lm.requestLocationUpdates(provider, minutes, 0, UpdateService.this);
        super.onCreate();

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onDestroy()
     */
    @Override
    public void onDestroy() {
        MyLog.d(TAG, "Stop service");
        this.stopSelf();
        super.onDestroy();
    }

    @Override
    public void onLocationChanged(Location location) {

        MyLog.d(TAG, " ist location null? <" + (location == null) + ">");
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            height = location.getAltitude();
            coordinates = new HashMap<String, String>();
            coordinates.put("lat", String.valueOf((double) Math.round(latitude * 10000) / 10000));
            coordinates.put("long", String.valueOf((double) Math.round(longitude * 10000) / 10000));
            coordinates.put("height", String.valueOf(height));
            MyLog.d(TAG, "sende Daten");
            sendData(coordinates);
            

        }
        turnGPSOff();

    }

    @Override
    public void onProviderDisabled(String provider) {
        try {
            Thread.sleep(minutes);
            turnGPSOn();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        super.onStartCommand(intent, flags, startId);

        return Service.START_NOT_STICKY;

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    // automatic turn off the gps
    public void turnGPSOff() {
        MyLog.d(TAG, "Schalte GPS aus");
        String provider = android.provider.Settings.Secure.getString(this.getContentResolver(),
                android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (provider.contains("gps")) { // if gps is enabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            this.sendBroadcast(poke);
        }
    }

    public void turnGPSOn() {
        MyLog.d(TAG, "Schalte GPS an");

        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
        this.sendBroadcast(intent);

        String provider = android.provider.Settings.Secure.getString(this.getContentResolver(),
                android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            this.sendBroadcast(poke);

        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnected();
    }

    private void sendData(final HashMap<String, String> data) {
        MyLog.i(TAG, "Updateservice aktiv!");
        MyLog.i(TAG, "Ist data leer? <" + data.isEmpty() + ">");
        if (data != null) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    final SharedPreferences sharedPrefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    String ip = sharedPrefs.getString("server_ip", null);
                    int port = Integer.parseInt(sharedPrefs.getString("server_port", "80"));
                    String name = sharedPrefs.getString("name", null);
                    String group = sharedPrefs.getString("group", null);
                    boolean setStartingPoint = sharedPrefs.getBoolean("setStartingPoint", false);
                    MyLog.d(TAG, "Startpunkt ist <" + setStartingPoint + ">");
                    if (setStartingPoint) {
                        SharedPreferences.Editor editor = sharedPrefs.edit();
                        editor.putBoolean("setStartingPoint", false);
                        editor.commit();
                    }
                    int minutes = Integer.parseInt(sharedPrefs.getString("intervall", "10"));

                    if (setStartingPoint) {
                        MyLog.d(TAG, "Startpunkt setzen");
                        name = "Startpunkt";
                    }

                    if (name != null && group != null && ip != null) {
                        if (isNetworkAvailable()) {
                            ch = new ConnectionHandler(ip, port);
                            String s = ch.buildGetString(name, group,
                                    (double) Math.round(Double.parseDouble(coordinates.get("lat")) * 10000) / 10000,
                                    (double) Math.round(Double.parseDouble(coordinates.get("long")) * 10000) / 10000,
                                    Double.parseDouble(coordinates.get("height")), System.currentTimeMillis(),
                                    ((setStartingPoint) ? "1" : "0"), "update-data");
                            MyLog.d(TAG, s);
                            ch.persistData(ch.sendRequest(s));

                            try {
                                Thread.sleep(minutes);
                            } catch (InterruptedException e) {
                                MyLog.e(TAG, e.getMessage());
                            }
                        }
                    }
                    

                }

            }).start();
           
           
        }

    }

}
